
import { _decorator, Component, Node, director, Label, tween, clamp, Sprite } from 'cc';
import { Clips, Key, aaEvent, storageKey, ui } from '../frame/common/Enums';
import { aa } from '../frame/FrameCore';
import configs from '../Configs';

const { ccclass, property } = _decorator;

@ccclass('TopView')
export class TopView extends Component {
    @property(Label) nameLabel: Label;
    @property(Label) cashLabel: Label;
    @property(Label) diamondLabel: Label;
    @property(Label) cpLabel:Label;
    @property(Sprite) heartsSP:Sprite;
    @property(Node) coin:Node;
    static ins:TopView;
    _cash: number = 0;
    _diamond: number = 0;
    _cp:number = 0;

    set cash(v) {
        v = Math.floor(v);
        this._cash = v;
        this.cashLabel.string = "" + v;
    }
    get cash() {
        return this._cash;
    }
    set diamond(v) {
        v = Math.floor(v);
        this._diamond = v;
        this.diamondLabel.string = "" + v;
    }
    get diamond() {
        return this._diamond;
    }

    set cp(v) {
        v = Math.floor(v);
        this._cp = v;
        this.cpLabel.string = "" + v;
    }
    get cp() {
        return this._cp;
    }
    set hearts(v){
        this._hearts = v;
        const h = Math.floor(v/6);
        this.heartsSP.fillRange = v/6+h*0.03;
    }
    get hearts(){
        return this._hearts;
    }
    private _hearts =0.5;
    onEnable() {
        this.cash = aa.data.get(Key.Cash);
        // this.diamond = data.get(Key.Diamond);
        this.nameLabel.string = configs.userName;
        TopView.ins = this;
        this.hearts = aa.data.get(Key.Hearts);
        director.on(aaEvent.currency, this.addCurrency, this);
        director.on(aaEvent.hearts, this.addHearts, this);
    }


    onDisable(): void {
        TopView.ins = null;
        director.off(aaEvent.currency, this.addCurrency, this);
        director.off(aaEvent.hearts, this.addHearts, this);

    }
    
    addHearts(num:number){
        const self = this.getComponent(TopView);
        let time = Math.abs(num - this._hearts)/2;
        tween(self).to(time, { hearts: num }).start();
    }

    addCurrency(key: storageKey, num: number) {
        num = num || 0;
        const self = this.getComponent(TopView);
        let time;
        switch (key) {
            case Key.Cash:
                time = clamp(Math.abs(num - this.cash) / 30,0.5,2);
                aa.data.set(Key.Cash,num);
                tween(self).to(time, { cash: num }).start();
                break;
            case Key.Diamond:
                time = clamp(Math.abs(num - this.diamond) / 200,0.4,0.7);
                tween(self).to(time, { diamond: num }).start();
                break;
        }
    }



}

